(function ($){
    var curDivIndex = 0;
    var nextDivIndex = 0;
    var collAdDiv;
    var interval;
    var intervalTime;
    var controlPanelButtons;
    var paused = false;
    
    $.fn.createTimedAdPanel = function(buttons, time)
    {
        controlPanelButtons = buttons;
        collAdDiv = $(this).children();
        $(collAdDiv).hide();
        intervalTime = time;
        interval = setInterval(animateAdPanel, intervalTime);
        
        animateAdPanel();
    };
    
    function animateAdPanel()
    {
        var curDiv = collAdDiv[curDivIndex];
        var nextDiv = collAdDiv[nextDivIndex];
        
        $(controlPanelButtons[curDivIndex]).removeClass("classActivePanelButton");
        $(controlPanelButtons[nextDivIndex]).addClass("classActivePanelButton");
        
        $(curDiv).fadeOut(200,
            function(){
                $(nextDiv).fadeIn(200);
            });
        
        curDivIndex = nextDivIndex;
        nextDivIndex = ++nextDivIndex%$(collAdDiv).length;
    }
    
    function resetInterval()
    {
        if(paused)
            return;
        
        clearInterval(interval);
        interval = setInterval(animateAdPanel, intervalTime);
    }
    
    $.fn.showSelectedAd = function()
    {
        resetInterval();
                
        var nextIndex = $(controlPanelButtons).index($(this)[0]);
        
        if(nextIndex === curDivIndex)
            return;
        
        nextDivIndex = $(controlPanelButtons).index($(this)[0]);
        animateAdPanel();
    };
    
    $.fn.showPreviousAd = function()
    {
        nextDivIndex = curDivIndex === 0 ? $(controlPanelButtons).length-1 : curDivIndex-1;
        resetInterval();
        animateAdPanel();
    };
    
    $.fn.showNextAd = function()
    {
        nextDivIndex = curDivIndex === $(controlPanelButtons).length-1 ? 0 : curDivIndex+1;
        resetInterval();
        animateAdPanel();
    };
    
    $.fn.pausePanel = function()
    {
        clearInterval(interval);
        paused = true;
    };
    
    $.fn.playPanel = function()
    {
        paused = false;
        resetInterval();
        animateAdPanel();
    };
    
    
    
}( jQuery ));